<template>
  <div v-if="row" class="drag-item" ref="dragItem">
      <ul>
        <li class="item">
          姓名: {{row.name}}
        </li>
      </ul>
  </div>
</template>

<script>
  export default {
    name: 'dragItem',
    props: {
      startPos: {
        type: Object,
        default: () => {
          return {
            x: 0,
            y: 0
          }
        }
      },
      row: {
        type: Object
      },
      onDragUp: {
        type: Function
      }
    },
    mounted() {
      this.addEvent()
    },
    methods: {
      setPosition(x,y) {
        const self = this.$refs.dragItem
        if (!this.dragItemStyle ) {
          this.dragItemStyle = {
            height: self.clientHeight,
            width: self.clientWidth
          }
        }
        self.style.top = (y - this.dragItemStyle.height / 2) + 'px'
        self.style.left = (x -   this.dragItemStyle.width / 2) + 'px'
      },
      dragMove(e) {
        const x = e.clientX
        const y = e.clientY
        this.setPosition(x, y)
      },
      dragUp(e) {
        // 执行传入的回调函数
        this.onDragUp(e,this.row)
        this.$el.remove()
        this.removeEvent()
      },
      addEvent() {
        document.body.addEventListener('mousemove',this.dragMove)
        document.body.addEventListener('mouseup',this.dragUp)
      },
      removeEvent() {
        document.body.removeEventListener('mousemove', this.dragMove)
        document.body.removeEventListener('mouseup', this.dragUp)
      }
    }
  }
</script>

<style lang="stylus" scoped>
  .drag-item
    position fixed
    padding 20px
    background #fff
    z-index 99
    box-shadow 0 0 8px #ddd
    cursor: pointer
    box-sizing border-box
    .item
      font-weight 700
</style>
